package net.xxcl.kygl.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import jxl.Cell;
import net.xxcl.kygl.mapper.ProjectMapper;
import net.xxcl.kygl.mapper.ProjectTypeMapper;
import net.xxcl.kygl.mapper.UserMapper;
import net.xxcl.kygl.mapper.UserProjectMapper;
import net.xxcl.kygl.model.ProjectForList;
import net.xxcl.kygl.model.ProjectForUser;
import net.xxcl.kygl.pojo.*;
import net.xxcl.kygl.util.CheckStr;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional()
public class ProjectService {
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private ProjectTypeMapper projectTypeMapper;
    @Autowired
    private UserProjectMapper userProjectMapper;
    @Autowired
    private UserMapper userMapper;

    private static final Logger logger = LoggerFactory.getLogger(ProjectService.class);

    @Transactional(readOnly = true)
    public int countByExample(Criteria example) {
        int count = this.projectMapper.countByExample(example);
        logger.debug("count: {}", count);
        return count;
    }

    @Transactional(readOnly = true)
    public Project selectByPrimaryKey(Integer id) {
        return this.projectMapper.selectByPrimaryKey(id);
    }

    @Transactional(readOnly = true)
    public List<Project> selectByExample(Criteria example) {
        return this.projectMapper.selectByExample(example);
    }

    public int deleteByPrimaryKey(Integer id) {
        return this.projectMapper.deleteByPrimaryKey(id);
    }

    public int updateByPrimaryKeySelective(Project record) {
        return this.projectMapper.updateByPrimaryKeySelective(record);
    }

    public int updateByPrimaryKey(Project record) {
        return this.projectMapper.updateByPrimaryKey(record);
    }

    public int deleteByExample(Criteria example) {
        return this.projectMapper.deleteByExample(example);
    }

    public int updateByExampleSelective(Project record, Criteria example) {
        return this.projectMapper.updateByExampleSelective(record, example);
    }

    public int updateByExample(Project record, Criteria example) {
        return this.projectMapper.updateByExample(record, example);
    }

    public int insert(Project record) {
        return this.projectMapper.insert(record);
    }

    public int insertSelective(Project record) {
        return this.projectMapper.insertSelective(record);
    }

    /**
     * 根据用户id查询记录
     */
    @Transactional(readOnly = true)
    public List<ProjectForUser> selectByUserId(Criteria example){
        return this.projectMapper.selectByUserId(example);
    }

    @Transactional(readOnly = true)
    public int countByUserId(Criteria example) {
        int count = this.projectMapper.countByUserId(example);
        logger.debug("count: {}", count);
        return count;
    }

    @Transactional(readOnly = true)
    public List<ProjectForList> selectList(Criteria example){
        return this.projectMapper.selectList(example);
    }

    @Transactional(readOnly = true)
    public int countList(Criteria example) {
        int count = this.projectMapper.countList(example);
        logger.debug("count: {}", count);
        return count;
    }

    /**
     * 增加院级课题
     * @param record
     * @param ids
     * @return
     */
    public int addProject(Project record,String ids) {
        this.projectMapper.insertSelective(record);
        String[] str = ids.split(",");
        UserProject userProject = new UserProject();
        userProject.setProjectid(record.getId());
        for(int i=0;i<str.length;i++){
            userProject.setRank(i+1);
            userProject.setUserid(Integer.parseInt(str[i]));
            this.userProjectMapper.insert(userProject);
        }
        return 1;
    }

    /**
     * 增加其它纵向课题
     * @param record
     * @param ids
     * @return
     */
    public int addOtherProject(Project record,String ids) {
        this.projectMapper.insertSelective(record);
        String[] str = ids.split(",");
        UserProject userProject = new UserProject();
        userProject.setProjectid(record.getId());
        for(int i=0;i<str.length;i++){
            userProject.setRank(i+1);
            userProject.setUserid(Integer.parseInt(str[i]));
            this.userProjectMapper.insert(userProject);
        }
        return 1;
    }

    public int addCrossProject(Project record,String approvedept,String ids) {
        ProjectType projectType = new ProjectType();
        projectType.setIscross(true);
        projectType.setApprovedept(approvedept);
        this.projectTypeMapper.insert(projectType);

        record.setProjecttype(projectType.getId());
        this.projectMapper.insertSelective(record);
        String[] str = ids.split(",");
        UserProject userProject = new UserProject();
        userProject.setProjectid(record.getId());
        for(int i=0;i<str.length;i++){
            userProject.setRank(i+1);
            userProject.setUserid(Integer.parseInt(str[i]));
            this.userProjectMapper.insert(userProject);
        }
        return 1;
    }

    /**
     * 查询课题有哪些参与人
     */
    public List<Map> getUserByProjectId(Integer projectId){
        return projectMapper.getUserByProjectId(projectId);
    }

    /**
     * 导入excel的一行记录
     * @param cells
     * @return
     */
    public Boolean saveExcelRow(Cell[] cells){
        try{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
            Criteria criteria = new Criteria();
            Project project = new Project();
            String projectTypeName = cells[0].getContents().trim();
            String remarks = cells[1].getContents().trim();
            String name = cells[2].getContents().trim();
            String dept = cells[3].getContents().trim();
            String lxDate = cells[6].getContents().trim();
            String planDate = cells[7].getContents().trim();
            String endDate = cells[8].getContents().trim();
            String stateStr = cells[9].getContents().trim();
            String money = cells[11].getContents().trim();
            String schoolMoney = cells[12].getContents().trim();
            String names = cells[13].getContents().trim();
            String description = cells[14].getContents().trim();
            if(projectTypeName.equalsIgnoreCase("") || remarks.equalsIgnoreCase("") || name.equalsIgnoreCase("")){
                throw new RuntimeException("课题类型、编号、名称不能为空");
            }
            criteria.put("remarks",remarks);
            //此处查询课题编号是否已经存在
            if(projectMapper.selectByExample(criteria).size()>0){
                throw new RuntimeException("课题编号"+remarks+"已经存在");
            }

            if(projectTypeName.equalsIgnoreCase("横向课题")){
                ProjectType projectType = new ProjectType();
                projectType.setIscross(true);
                projectType.setApprovedept(dept);
                projectTypeMapper.insertSelective(projectType);
                project.setProjecttype(projectType.getId());
            } else {
                criteria.clear();
                criteria.put("name",projectTypeName);
                List<ProjectType> projectTypes = projectTypeMapper.selectByExample(criteria);
                if(projectTypes.size()>0){
                    project.setProjecttype(projectTypes.get(0).getId());
                } else {
                    throw new RuntimeException("课题类型"+projectTypeName+"不存在");
                }
            }

            project.setRemarks(remarks);
            project.setName(name);
            if(!lxDate.equals("")){
                project.setApprovaltime(sdf.parse(lxDate));
            }
            if(!planDate.equals("")){
                project.setPlanendtime(sdf.parse(planDate));
            }
            if(!endDate.equals("")){
                project.setEndtime(sdf.parse(endDate));
            }
            if(stateStr.equals("在研")){
                project.setState(3);
            } else {
                project.setState(11);
            }
            if(!money.equalsIgnoreCase("")){
                project.setMoney(Double.parseDouble(money));
            }
            if(!schoolMoney.equalsIgnoreCase("")){
                project.setMoney(Double.parseDouble(schoolMoney));
            }
            if(!description.equalsIgnoreCase("")){
                project.setDescription(description);
            }

            projectMapper.insertSelective(project);

            UserProject userProject = new UserProject();
            userProject.setProjectid(project.getId());
            names = names.replaceAll("，",",").replaceAll("（","(").replaceAll("）",")");
            String[] peoples = names.split(",");
            for(int i=0;i<peoples.length;i++){
                userProject.setRank(i+1);
                String people = peoples[i].trim();
                if(people.startsWith("(")){
                    people = people.substring(1,people.length());
                    User user = new User();
                    user.setUsername(people);
                    user.setIscolleague(false);
                    userMapper.insertSelective(user);
                    userProject.setUserid(user.getId());
                    userProjectMapper.insertSelective(userProject);
                } else {
                    criteria.clear();
                    List<User> users = new ArrayList<User>();
                    if(CheckStr.isNumeric(people)){
                        //用工号查找
                        criteria.put("name",people);
                        users = userMapper.selectByExample(criteria);
                    } else {
                        //用姓名查找，可能会有重名
                        criteria.put("username",people);
                        users = userMapper.selectByExample(criteria);
                    }
                    if(users.size()==1){
                        userProject.setUserid(users.get(0).getId());
                        userProjectMapper.insertSelective(userProject);
                    } else if(users.size()>1) {
                        throw new RuntimeException("用户姓名"+people+"有重名，请用工号代替");
                    } else {
                        throw new RuntimeException("用户"+people+"不存在");
                    }
                }
            }
            return true;
        } catch (RuntimeException e){
            throw e;
        } catch (ParseException e) {
            e.printStackTrace();
            return false;
        }
    }
}